const mysql = require('mysql')
const NodeUtil = require('util')
const { DB } = require('./config')
const runtimeLogger = require('./log4js')()

const conn = mysql.createConnection(Object.assign({}, DB, {
  typecast:
    (field, next) => {
      if (field.type === 'JSON') {
        return (JSON.parse(field.string()))
      }
      return next()
    }
}))
const PromiseConn = NodeUtil.promisify(conn.query).bind(conn)

conn.connect(err => {
  if (err) {
    console.error('error connecting: ' + err.stack)
    return
  }
  console.log('connected as id ' + conn.threadId)
})

/**
 * 查询数据
 * @param where 查询条件
 * @returns {Promise<void>}
 */
function query(table, where = '1 = 1') {
  const sql = `SELECT * FROM ${table} WHERE ${where}`
  const log = `Begin query table ${table}. sql: ${sql}`
  runtimeLogger.info(log)
  return PromiseConn(sql)
}

/**
 * 插入数据
 * @param table 表名
 * @param params insert 参数
 * @returns {Promise<void>}
 */
function insert(table, params) {
  const sql = `INSERT INTO ${table} SET ?`
  const log = `Begin insert table ${table}. sql: ${sql}`
  runtimeLogger.info(log)
  return PromiseConn(sql, params)
}

/**
 * 更新数据
 * @param table 表名
 * @param action set语句
 * @param where 条件
 */
function update(table, action, where = `1 = 1`) {
  const sql = `UPDATE ${table} SET ${action} WHERE ${where}`
  const log = `Begin update table ${table}. sql: ${sql}`
  runtimeLogger.info(log)
  return PromiseConn(sql)
}

/**
 * 删除数据
 */
function del(table, where = `1 = 1`) {
  const sql = `DELETE FROM ${table} WHERE ${where}`
  const log = `Begin delete table ${table}. sql: ${sql}`
  runtimeLogger.info(log)
  return PromiseConn(sql)
}

module.exports = { query, insert, update, del }
